package com.alibaba.citrus.cr.mn.order.center.facade.service.impl;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.enums.ordercenter.*;
import com.alibaba.citrus.cr.mn.order.center.common.util.AssertUtils;
import com.alibaba.citrus.cr.mn.order.center.common.util.StopWatchUtils;
import com.alibaba.citrus.cr.mn.order.center.forecastorder.ForecastOrderBizDomainService;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.mnordercenter.forecastorderbiz.service.ForecastOrderBizService;
import com.epoch.app.mnordercenter.model.dto.*;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@Primary
public class ForecastOrderBizServiceImpl implements ForecastOrderBizService {
    private static final Log log = Log.getLogger(ForecastOrderBizServiceImpl.class);

    // 初始化B-b的预报订单类型集合
    private static final List<String> forecastOrderTypeList = Lists.newArrayList(ForecastOrderTypeEnum.STD_FORECAST.getCode(), ForecastOrderTypeEnum.REPLENISH_FORECAST.getCode());

    @Resource
    private ForecastOrderBizDomainService forecastOrderBizDomainService;

    @Override
    @FacadeInvoker
    public Result<ForecastBizAsyncResponse> batchCreate(ForecastOrderBizBatchCreateRequest request) {
        // 设置B-b一盘货预报订单缺省值
        List<CreateForecastDTO> createForecastDTOs = request.getCreateForecastOrderDTOS();
        log.info("createForecastDTOs参数:{}", JSON.toJSONString(createForecastDTOs));
        AssertUtils.isTrue(CollectionUtils.isEmpty(createForecastDTOs), "OC-01-001-01-15-001", "单据列表");
        createForecastDTOs.forEach(createForecastDTO -> {
            // 设置订单类型缺省
            createForecastDTO.setOrderCategoryCode(OrderCategoryEnum.COMPANY.getCode());
            // 设置订单类型
//            if (StringUtils.isBlank(createForecastDTO.getSalesOrderType())){
//                createForecastDTO.setSalesOrderType(ForecastOrderTypeEnum.STD_FORECAST.getCode());
//            }
            //设置默认履约方式
            if (StringUtils.isBlank(createForecastDTO.getFulfillmentTypeCode())){
                createForecastDTO.setFulfillmentTypeCode(FulfillmentTypeEnum.EXTERNAL_TO_DELIVERY.getCode());
            }
            if (StringUtils.isBlank(createForecastDTO.getFulfillmentPriority())){
                createForecastDTO.setFulfillmentPriority(FulfillmentPriorityEnum.NORMAL.getCode());
            }
            if (StringUtils.isBlank(createForecastDTO.getAutoFulfillment())){
                createForecastDTO.setAutoFulfillment(Boolean.TRUE.toString());
            }
            if(StringUtils.isBlank(createForecastDTO.getOrderChannelCode())){
                createForecastDTO.setOrderChannelCode(OrderChannelEnum.COMPANY.getCode());
            }
        });
        return buildSuccessResult(forecastOrderBizDomainService.batchCreate(request));
    }

    public Result<ForecastBizSyncResponse> create(ForecastOrderBizCreateRequest request){
        CreateForecastDTO createForecastDTO = request.getCreateForecastOrderDTO();
        AssertUtils.isTrue(createForecastDTO == null, "OC-01-001-01-15-001", "预报订单");
        // 设置订单类型缺省
        createForecastDTO.setOrderCategoryCode(OrderCategoryEnum.COMPANY.getCode());
        // 设置订单类型
        if (StringUtils.isBlank(createForecastDTO.getSalesOrderType())){
            createForecastDTO.setSalesOrderType(ForecastOrderTypeEnum.STD_FORECAST.getCode());
        }
        //设置默认履约方式
        if (StringUtils.isBlank(createForecastDTO.getFulfillmentTypeCode())){
            createForecastDTO.setFulfillmentTypeCode(FulfillmentTypeEnum.CENTRAL_DELIVERY.getCode());
        }
        if (StringUtils.isBlank(createForecastDTO.getFulfillmentPriority())){
            createForecastDTO.setFulfillmentPriority(FulfillmentPriorityEnum.NORMAL.getCode());
        }
        if (StringUtils.isBlank(createForecastDTO.getAutoFulfillment())){
            createForecastDTO.setAutoFulfillment(Boolean.TRUE.toString());
        }
        Result<ForecastBizSyncResponse> result = forecastOrderBizDomainService.create(request);
        return result;
    }

    @Override
    public Result<ModifyForecastResponseDTO> modify(ModifyForecastRequest request) {
        ModifyForecastDTO modifyForecastDTO = Objects.isNull(request.getModifyForecastDTO())?new ModifyForecastDTO():request.getModifyForecastDTO();
        modifyForecastDTO.setOrderCategoryCode(OrderCategoryEnum.COMPANY.getCode());
        request.setModifyForecastDTO(modifyForecastDTO);
        return buildSuccessResult(forecastOrderBizDomainService.modify(request));
    }

    @Override
    public Result<List<SubmitForecastResponseDTO>> batchSubmit(ForecastBizBatchSubmitRequest request) {
        request.setForecastOrderTypeList(forecastOrderTypeList);
        return buildSuccessResult(forecastOrderBizDomainService.batchSubmit(request));
    }

    @Override
    public Result<QueryForecastResponse> query(QueryForecastRequest request) {
        request.setOrderCategoryCode(OrderCategoryEnum.COMPANY.getCode());
        //由于共用一个查询的缘故，导致B-b预报详情查询多了三个字段，将其置空
        Result<QueryForecastResponse> query = forecastOrderBizDomainService.query(request);
        if (Objects.nonNull(query.getResult())){
            QueryForecastResponse forecastResponse = query.getResult();
            forecastResponse.setCustomerGrade(null);
            forecastResponse.setCustomerGroup(null);
            forecastResponse.setCustomerGroupName(null);
        }
        return buildSuccessResult(query);
    }

    @Override
    public Result<List<CancelForecastResponseDTO>> batchCancel(CancelForecastRequest request) {
        request.setForecastOrderTypeList(forecastOrderTypeList);
        return buildSuccessResult(forecastOrderBizDomainService.batchCancel(request));
    }

    @Override
    public Result<List<PageQueryCompanyForecastDetailResponse>> pageQueryLine(PageQueryForecastLineRequest request) {

        if(CollectionUtils.isEmpty(request.getOrderTypeCodeList())){
            List<String> orderTypeCodeList = new ArrayList<>();
            orderTypeCodeList.add(ForecastOrderTypeEnum.STD_FORECAST.getCode());
            orderTypeCodeList.add(ForecastOrderTypeEnum.REPLENISH_FORECAST.getCode());
            request.setOrderTypeCodeList(orderTypeCodeList);
        }
        Result<List<PageQueryForecastDetailResponse>> result = forecastOrderBizDomainService.pageQueryLine(request, OrderCategoryEnum.COMPANY.getCode());
        List<PageQueryCompanyForecastDetailResponse> pageQueryCompanyForecastDetailResponses = new ArrayList<>();
        Result<List<PageQueryCompanyForecastDetailResponse>> companyResult = new Result<>();
        if(CollectionUtils.isNotEmpty(result.getResult())){
            result.getResult().forEach(detail -> {
                PageQueryCompanyForecastDetailResponse pageQueryCompanyForecastDetail = new PageQueryCompanyForecastDetailResponse();
                BeanUtils.copyProperties(detail, pageQueryCompanyForecastDetail);
                pageQueryCompanyForecastDetailResponses.add(pageQueryCompanyForecastDetail);
            });
        }
        companyResult.setSuccess(result.isSuccess());
        companyResult.setErrorCode(result.getErrorCode());
        companyResult.setMessage(result.getMessage());
        companyResult.setTotal(result.getTotal());
        if (result.isSuccess()) {
            companyResult.setResult(pageQueryCompanyForecastDetailResponses);
        }
        return buildSuccessResult(companyResult);
    }

    @Override
    public Result<List<QueryForecastResponse>> pageQuery(PageQueryForecastRequest request) {
        return buildSuccessResult(forecastOrderBizDomainService.pageQuery(request, OrderCategoryEnum.COMPANY.getCode()));
    }

    @Override
    public Result<List<ForecastOrderBizQueryAnalysisResponse>> queryAnalysis(ForecastOrderBizQueryAnalysisRequest request) {
        return buildSuccessResult(forecastOrderBizDomainService.queryAnalysis(request));
    }

    @Override
    public Result<AnalysisForecastResponseDTO> batchAnalysis(AnalysisForecastRequest request) {
        return buildSuccessResult(forecastOrderBizDomainService.batchAnalysis(request));
    }

    @Override
    public Result<List<ForecastOrderBizQueryActivityResponse>> batchQueryActivity(ForecastOrderBizBatchQueryActivityRequest request) {
        return buildSuccessResult(forecastOrderBizDomainService.batchQueryActivity(request));
    }

    @Override
    public Result<ForecastBizAsyncResponse> batchConfirm(ConfirmReplyRequest request) {
        return buildSuccessResult(forecastOrderBizDomainService.batchConfirm(request));
    }

    @Override
    public Result<List<ForecastReplyBizModifyResponse>> batchModifyReply(ForecastReplyBizBatchModifyRequest request) {
        request.setForecastOrderTypeList(forecastOrderTypeList);
        return buildSuccessResult(forecastOrderBizDomainService.batchModifyReply(request));
    }

    @Override
    public Result<List<ForecastOrderBizCloseResponse>> batchClose(ForecastOrderBizBatchCloseRequest request) {
        request.setForecastOrderTypeList(forecastOrderTypeList);
        return buildSuccessResult(forecastOrderBizDomainService.batchClose(request));
    }

    @Override
    public Result<List<ForecastOrderBizModifyActivityResponse>> batchModifyActivity(ForecastOrderBizBatchModifyActivityRequest request) {
        log.info("ForecastOrderBizServiceImpl#batchModifyActivity request={}", JSON.toJSONString(request));
        return buildSuccessResult(forecastOrderBizDomainService.batchModifyActivity(request));
    }

    /**
     * 请求成功时补充Message和ErrorCode，确保出参字段都存在
     */
    private <T> Result<T> buildSuccessResult(Result<T> result) {
        StopWatch stopWatch = StopWatchUtils.clear();
        if (Objects.nonNull(stopWatch)) {
            log.info("ForecastOrderBizServiceImpl#buildSuccessResult stopWatch.getTotalTimeSeconds()={}", stopWatch.getTotalTimeSeconds());
            log.info("ForecastOrderBizServiceImpl#buildSuccessResult stopWatch.prettyPrint()={}", stopWatch.prettyPrint());
        }

        if (result.isSuccess()) {
            result.setMessage("");
            result.setErrorCode("");
        }
        return result;
    }

    @Override
    public Result<List<ForecastBizGroupResponse>> syncBatchConfirm(ConfirmReplyFulfillRequest confirmReplyRequest){
        return buildSuccessResult(forecastOrderBizDomainService.syncBatchConfirm(confirmReplyRequest));

    }
}

